package com.party.web.web.controller.member;

import com.google.common.collect.Lists;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.city.City;
import com.party.core.model.commune.CRoute;
import com.party.core.model.commune.CRouteInfo;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.city.ICityService;
import com.party.core.service.commune.ICRouteInfoService;
import com.party.core.service.commune.ICRouteService;
import com.party.core.service.member.IMemberGroupService;
import com.party.web.biz.member.MemberMgmtService;
import com.party.web.biz.member.MemberRouteBizService;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CRouteInfoQuery;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.route.MemberRouteOutput;
import com.party.web.web.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 路线管理控制器
 *
 * @Date: 2019/10/22 15:07
 */
@Controller
@RequestMapping(value = "member/route")
public class MemberRouteController {

    @Autowired
    private ICRouteService routeService;

    @Autowired
    private MemberRouteBizService memberRouteBizService;

    @Autowired
    private ICityService cityService;

    @Autowired
    private MemberMgmtService memberMgmtService;

    @Autowired
    private ICRouteInfoService routeInfoService;

    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private MemberGroupBizService memberGroupBizService;

    Logger logger = LoggerFactory.getLogger(getClass());


    /***
     * 路线列表
     * @Date 13:45 2019/10/30
     * @param input
     * @param page
     * @return
     **/
    @RequestMapping("list")
    public ModelAndView list(CommonInput input, String memberGroupId, Page page) {
        page.setLimit(10);

        ModelAndView mv = new ModelAndView("member/routeList");
        Map<String, Object> params = CommonInput.appendParams(input);
        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }
        memberGroupId = memberGroupBizService.getXzgsMemberId();
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();

/*        List<MemberGroup> memberGroupList =  memberGroupService.getChildWithMyAndName(currentUser.getId());
        List<String> orgIds = LangUtils.transform(memberGroupList, input1 -> input1.getId());
        params.put("orgIds", orgIds);*/

        if (StringUtils.isNotEmpty(input.getRouteName())) {
            params.put("routeName", input.getRouteName());
        }
        params.put("memberGroupId", memberGroupId);
        List<CRoute> cRoutes = routeService.webPageList(params, page);

        for (CRoute cRoute : cRoutes) {
            Long dataTotal = routeInfoService.getDataTotalByRouteId(cRoute.getId());
            cRoute.setDataTotal(Integer.parseInt(dataTotal.toString()));
        }

        mv.addObject("input", input);
        mv.addObject("page", page);
        mv.addObject("cRoutes", cRoutes);
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        mv.addObject("isChild", currentUser.isChild());
        //mv.addObject("memberGroupList",memberGroupList);
        mv.addObject("memberGroupId", memberGroupId);

        return mv;
    }

    @RequestMapping("form")
    public ModelAndView form(String id) {
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        ModelAndView mv = new ModelAndView("member/routeForm");
        if (StringUtils.isNotEmpty(id)) {
            CRoute cRoute = routeService.get(id);
            mv.addObject("cRoute", cRoute);
        }
        City city = new City();
        city.setIsOpen(1);
        mv.addObject("citys", cityService.list(city));
        mv.addObject("isChild", currentUser.isChild());
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        return mv;
    }

    /***
     * 添加修改路线
     * @Date 13:45 2019/10/30
     * @param cRoute
     * @param cAreaInput
     * @param sAreaInput
     * @return
     **/
    @ResponseBody
    @RequestMapping("saveOrUpdate")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(CRoute cRoute, String cAreaInput, String sAreaInput, String memberGroupId) {

        String partnerId = memberGroupBizService.getXzgsMemberId();

        if (StringUtils.isEmpty(cRoute.getRouteName())) {
            return AjaxResult.error("路线名称为空");
        }
        if (StringUtils.isEmpty(cRoute.getsLat())) {
            return AjaxResult.error("起点未标记");
        }
        if (StringUtils.isEmpty(cRoute.getcLat())) {
            return AjaxResult.error("终点未标记");
        }

        //起点经纬度
        String sCoordinate = cRoute.getsLat() + "," + cRoute.getsLng();

        //终点经纬度
        String cCoordinate = cRoute.getcLat() + "," + cRoute.getcLng();

        if (StringUtils.isNotEmpty(sAreaInput)) {
            cRoute.setsArea(sAreaInput);
        }

        if (StringUtils.isNotEmpty(cAreaInput)) {
            cRoute.setcArea(cAreaInput);
        }

        cRoute.setOrigin(sCoordinate);
        cRoute.setDestination(cCoordinate);
        List<String> orgIds = memberGroupService.getChildWithMy(partnerId);
        try {
            //公司地址集合
            List<Map<String, Object>> allCompanyAddress = memberMgmtService.getAllCompanyAddress(orgIds, null);
            //家地址集合
            List<Map<String, Object>> homeAddress = memberMgmtService.getAllHomeAddress(orgIds, null);
            int companyAddressTotal = allCompanyAddress.size();
            int homeAddressTotal = homeAddress.size();
            //预计要生成的总条目数
            int total = companyAddressTotal * 4 + homeAddressTotal * 4;
            CRoute routeByName = routeService.getRouteByName(cRoute.getRouteName(), partnerId);
            if (StringUtils.isNotEmpty(cRoute.getId())) {

                CRoute dbroute = routeService.get(cRoute.getId());
                if (null != routeByName && !dbroute.getRouteName().equals(routeByName.getRouteName())) {
                    return AjaxResult.error("路线名称已存在");
                }

                String origin = dbroute.getOrigin();
                String destination = dbroute.getDestination();

                boolean b = StringUtils.isEmpty(memberGroupId) && sCoordinate.equals(origin) && cCoordinate.equals(destination);
                boolean b1 = StringUtils.isNotEmpty(memberGroupId) && dbroute.getCreateBy().equals(memberGroupId) && sCoordinate.equals(origin) && cCoordinate.equals(destination);

                if (b || b1) {
                    //地址没有改变，只更新，不删除数据和生成数据
                    MyBeanUtils.copyBeanNotNull2Bean(cRoute, dbroute);
                    routeService.update(dbroute);
                } else {
                    if (StringUtils.isNotEmpty(memberGroupId)) {
                        dbroute.setCreateBy(memberGroupId);
                    }
                    cRoute.setRouteInfoTotal(total);
                    //地址发生改变，更新，删除数据并重新生成
                    MyBeanUtils.copyBeanNotNull2Bean(cRoute, dbroute);
                    routeService.update(dbroute);
                    routeInfoService.deleteByRouteId(cRoute.getId());
                    memberRouteBizService.calDistanceAndTime(cRoute, allCompanyAddress, homeAddress, partnerId);
                }
                return AjaxResult.success("路线修改成功");
            }
            if (null != routeByName) {
                return AjaxResult.error("路线名称已存在");
            }
            cRoute.setRouteInfoTotal(total);
            //设置创建的机构
            cRoute.setCreateBy(partnerId);
            routeService.insert(cRoute);

            //计算路线到公司地址的驾驶距离和时间
            memberRouteBizService.calDistanceAndTime(cRoute, allCompanyAddress, homeAddress, partnerId);

        } catch (Exception e) {
            logger.error("添加编辑路线异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("添加编辑路线异常", e.getMessage());
        }
        return AjaxResult.success();
    }

    /***
     * 路线分析列表
     * @Date 13:45 2019/10/30
     * @param input
     * @param page
     * @return
     **/
    @RequestMapping("memberRouteList")
    public ModelAndView memberRouteList(CRouteInfoQuery input,Page page) {
        page.setLimit(10);
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();

        ModelAndView mv = new ModelAndView("member/routeInfoList");
        Map<String, Object> params = new HashMap<>();
        if (null == input.getType()) {
            input.setType(0);
            params.put("type", 0);
        }
        List<String> orgIds = Lists.newArrayList();
        //查询机构列表
        List<MemberGroup> memberGroups = new ArrayList<>();
        if (!currentUser.isChild()) {
            memberGroups = memberGroupService.getChildWithMyAndName(currentUser.getId());
            orgIds = LangUtils.transform(memberGroups, input1 -> input1.getId());
        }else if(currentUser.isXzgsAdmin()){
            memberGroups = memberGroupService.queryAdminBranchAndXZGSList(currentUser.getId(),null);
            orgIds = LangUtils.transform(memberGroups, input1 -> input1.getId());
        }
        mv.addObject("memberGroupList", memberGroups);


        //查询所有路线
        params.put("partnerId", memberGroupBizService.getXzgsMemberId());
        List<CRoute> cRouteList = routeService.webPageList(params, null);


       //查询当前机构下所有路线的时间和距离
        if(StringUtils.isNotEmpty(input.getMemberGroupId())){
            orgIds.clear();
            orgIds.add(input.getMemberGroupId());
        }
        if(orgIds.size()==0){
            orgIds.add(currentUser.getId());
        }

        params.put("orgIds", orgIds);
        params.put("type", input.getType());
        params.put("routeId", input.getRouteId());

        if (StringUtils.isNotEmpty(input.getNickName())) {
            params.put("nickName", input.getNickName());
        }

        List<Map<Integer, Integer>> typeList = memberRouteBizService.getRouteTypeList(input.getRouteFlag(), input.getAddressType());


        List<CRouteInfo> routeInfoList = routeInfoService.getMemberListPage(params, page);

        List<MemberRouteOutput> routeOutputs = LangUtils.transform(routeInfoList, input1 -> {
            MemberRouteOutput output = new MemberRouteOutput();
            try {
                com.party.core.utils.MyBeanUtils.copyBeanNotNull2Bean(input1, output);
            } catch (Exception e) {
                e.printStackTrace();
            }

            params.put("memberId", input1.getMemberId());

            List<MemberRouteOutput.RouteDetailOutput> outputs = Lists.newArrayList();
            for (Map<Integer, Integer> map : typeList) {
                MemberRouteOutput.RouteDetailOutput detailOutput = new MemberRouteOutput().new RouteDetailOutput();
                for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                    Integer addressType1 = entry.getKey();
                    Integer routeFlag = entry.getValue();
                    params.put("routeFlag", routeFlag);
                    params.put("addressType", addressType1);
                    params.put("travelType", input.getTravelType());
                    List<CRouteInfo> list = routeInfoService.getDetailRouteList(params);
                    for (CRouteInfo cRouteInfo : list) {
                        if (cRouteInfo.getTravelType().equals(0)) {
                            detailOutput.setBus(cRouteInfo);
                        } else if (cRouteInfo.getTravelType().equals(1)) {
                            detailOutput.setDriver(cRouteInfo);
                        }
                    }

                    detailOutput.setRouteFlag(routeFlag);
                    detailOutput.setAddressType(addressType1);
                }

                outputs.add(detailOutput);
            }

            output.setDataList(outputs);

            return output;
        });
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        mv.addObject("isChild", currentUser.isChild());
        mv.addObject("cRouteList", cRouteList);
        mv.addObject("routeInfoList", routeOutputs);
        mv.addObject("routeInfoList", routeOutputs);
        mv.addObject("input", input);
        mv.addObject("page", page);
        return mv;
    }

    /***
     * 删除路线并删除路线下对应的数据
     * @Date 13:46 2019/10/30
     * @param id
     * @return
     **/
    @ResponseBody
    @RequestMapping("delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {

        try {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("参数为空");
            }
            routeService.deleteLogic(id);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    routeInfoService.deleteByRouteId(id);
                }
            });

        } catch (Exception e) {
            logger.error("删除路线异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除路线失败");
        }
        return AjaxResult.success("删除成功");
    }

    /***
     * 重新初始化生成路线下的数据
     * @Date 19:25 2019/11/1
     * @param id
     * @return
     **/
    @ResponseBody
    @RequestMapping("initData")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult initData(String id) {
        String partnerId = memberGroupBizService.getXzgsMemberId();
        try {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("参数为空");
            }
            CRoute route = routeService.get(id);
            if (StringUtils.isNotEmpty(route.getCreateBy())) {
                partnerId = route.getCreateBy();
            }
            List<String> orgIds = memberGroupService.getChildWithMy(partnerId);
            //公司地址集合
            List<Map<String, Object>> allCompanyAddress = memberMgmtService.getAllCompanyAddress(orgIds, null);
            //家地址集合
            List<Map<String, Object>> homeAddress = memberMgmtService.getAllHomeAddress(orgIds, null);
            int companyAddressTotal = allCompanyAddress.size();
            int homeAddressTotal = homeAddress.size();
            //预计要生成的总条目数
            int total = companyAddressTotal * 4 + homeAddressTotal * 4;
            CRoute cRoute = routeService.get(id);
            cRoute.setRouteInfoTotal(total);
            //更新路线信息
            routeService.update(cRoute);
            //删除旧数据
            routeInfoService.deleteByRouteId(cRoute.getId());
            //生成新的数据
            memberRouteBizService.calDistanceAndTime(cRoute, allCompanyAddress, homeAddress, partnerId);

        } catch (Exception e) {
            logger.error("初始化路线数据失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("初始化路线数据失败");
        }
        return AjaxResult.success("生成数据中");
    }

}
